<template>
  <div class="client-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>客户管理</span>
          <el-button type="primary" @click="handleAdd">新增客户</el-button>
        </div>
      </template>
      
      <el-table
        :data="clients"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="客户编码" prop="clientCode" width="120" />
        <el-table-column label="公司名称" prop="companyName" />
        <el-table-column label="联系人" prop="contactName" />
        <el-table-column label="联系电话" prop="contactPhone" />
        <el-table-column label="信用等级">
          <template #default="scope">
            <el-tag :type="getCreditTypeClass(scope.row.creditRating)">
              {{ scope.row.creditRating }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑客户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="clientForm" label-width="100px" :rules="formRules" ref="clientFormRef">
        <el-form-item label="客户编码" prop="clientCode">
          <el-input v-model="clientForm.clientCode" placeholder="请输入客户编码"></el-input>
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="clientForm.companyName" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="clientForm.contactName" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="clientForm.contactPhone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="信用等级" prop="creditRating">
          <el-select v-model="clientForm.creditRating" placeholder="请选择信用等级">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同开始日期" prop="contractStart">
          <el-date-picker
            v-model="clientForm.contractStart"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ClientList',
  setup() {
    const store = useStore()
    const router = useRouter()
    const clients = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增客户')
    const clientFormRef = ref(null)
    
    // 客户表单数据
    const clientForm = reactive({
      clientId: null,
      clientCode: '',
      companyName: '',
      contactName: '',
      contactPhone: '',
      creditRating: 'B',
      contractStart: ''
    })
    
    // 表单验证规则
    const formRules = {
      clientCode: [
        { required: true, message: '请输入客户编码', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      companyName: [
        { required: true, message: '请输入公司名称', trigger: 'blur' }
      ],
      contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' }
      ],
      contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      contractStart: [
        { required: true, message: '请选择合同开始日期', trigger: 'change' }
      ]
    }
    
    // 根据信用等级返回对应的标签类型
    const getCreditTypeClass = (creditRating) => {
      const map = {
        'A': 'success',
        'B': 'primary',
        'C': 'warning',
        'D': 'danger'
      }
      return map[creditRating] || 'info'
    }
    
    // 获取客户列表数据
    const fetchClients = async () => {
      loading.value = true
      try {
        await store.dispatch('fetchClients')
        clients.value = store.getters.clients
        console.log('获取到的客户数据:', clients.value)
      } catch (error) {
        console.error('获取客户列表失败:', error)
        ElMessage.error('获取客户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      clientForm.clientId = null
      clientForm.clientCode = ''
      clientForm.companyName = ''
      clientForm.contactName = ''
      clientForm.contactPhone = ''
      clientForm.creditRating = 'B'
      clientForm.contractStart = ''
      if (clientFormRef.value) {
        clientFormRef.value.resetFields()
      }
    }
    
    // 新增客户
    const handleAdd = () => {
      dialogTitle.value = '新增客户'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑客户
    const handleEdit = (client) => {
      dialogTitle.value = '编辑客户'
      Object.assign(clientForm, client)
      dialogVisible.value = true
    }
    
    // 查看客户详情
    const handleView = (client) => {
      router.push(`/clients/${client.clientId}`)
    }
    
    // 删除客户
    const handleDelete = (client) => {
      ElMessageBox.confirm(
        `确认删除客户"${client.companyName}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.delete(`/clients/${client.clientId}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchClients()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除客户失败:', error)
          ElMessage.error('删除客户失败')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!clientFormRef.value) return
      
      try {
        await clientFormRef.value.validate()
        
        if (clientForm.clientId) {
          // 编辑现有客户
          const response = await axios.put(`/clients/${clientForm.clientId}`, clientForm)
          if (response.data.code === 200) {
            ElMessage.success('更新客户成功')
            dialogVisible.value = false
            fetchClients()
          } else {
            ElMessage.error(response.data.message || '更新客户失败')
          }
        } else {
          // 新增客户
          const response = await axios.post('/clients', clientForm)
          if (response.data.code === 200) {
            ElMessage.success('添加客户成功')
            dialogVisible.value = false
            fetchClients()
          } else {
            ElMessage.error(response.data.message || '添加客户失败')
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }
    
    onMounted(() => {
      fetchClients()
    })
    
    return {
      clients,
      loading,
      dialogVisible,
      dialogTitle,
      clientForm,
      clientFormRef,
      formRules,
      handleAdd,
      handleView,
      handleEdit,
      handleDelete,
      submitForm,
      getCreditTypeClass
    }
  }
}
</script>

<style scoped>
.client-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>